<template>
    <div class="tool-copy-container" :style="toolPosition">
        <!-- 拖拽部分 -->
        <div class="tool-copy-drag" @mousedown="startDragging">
            <i class="iconfont icon-drag"></i>
        </div>

        <div class="tool-copy-item" v-for="(item, index) in tools" :key="index" @click="handleCopy(item)">
            <el-tooltip
                class="box-item"
                effect="dark"
                :content="'复制到' + item.name"
                placement="left"
            >
                <i class="iconfont" :class="item.icon" :style="{color: item.color}"></i>
            </el-tooltip>
        </div>

        <div class="juejin-theme-confirm" v-if="isShowJuejinConfirm">
            <div class="confirm-title">掘金不允许插入HTML代码，所以请选择下方掘金官方主题</div>
            <el-select size="small" placeholder="请选择" v-model="juejinTheme">
                <el-option v-for="(item, index) in juejinMarkdownThemeConfig" :key="index" :label="item"
                           :value="item"></el-option>
            </el-select>
            <div class="confirm-footer">
                <el-button type="danger" size="small" @click="closeJuejinConfirm">取消</el-button>
                <el-button type="primary" size="small" @click="handleSubmitJuejinTheme">确定</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import {reactive, ref, defineProps, onMounted, nextTick} from "vue";
import {copyToClipboard, solveHtml, solveWeChatMath} from "../utils/converter.js";
import juejinMarkdownThemeConfig from "../config/juejinMarkdownThemeConfig.js";
import {ElMessage} from "element-plus";
import {useSystemStore} from "../store/index.js";

const props = defineProps({
    text: String
})

const systemStore = useSystemStore();

// 工具列表数据
const tools = reactive([
    {
        name: '公众号',
        title: 'wechat',
        icon: 'icon-wechat',
        color: '#07C874',
        url: 'https://mp.weixin.qq.com/'
    },
    {
        name: '掘金',
        title: 'juejin',
        icon: 'icon-juejin',
        color: '#1E80FF',
        url: 'https://juejin.cn/editor/drafts/new?v=2'
    },
    {
        name: '知乎',
        title: 'zhihu',
        icon: 'icon-zhihu',
        color: '#0066FF',
        url: 'https://zhuanlan.zhihu.com/write'
    },
    {
        name: 'CSDN',
        title: 'csdn',
        icon: 'icon-csdn',
        color: '#CE000D',
        url: 'https://editor.csdn.net/md/'
    },
]);

// 初始位置
const toolPosition = reactive({
    top: '300px',
    right: '20px'
});

const isShowJuejinConfirm = ref(false);
const juejinTheme = ref('');

// 拖拽相关状态
// 定义一个响应式的布尔变量，用于追踪是否正在拖动
const isDragging = ref(false);
// 定义一个响应式的对象，用于存储拖动偏移量
const dragOffset = reactive({
    x: 0,
    y: 0
});

onMounted(() => {
    nextTick(() => {
        juejinTheme.value = systemStore.defautJuejinTheme;
    })
})

/**
 * 开始拖动的函数
 * @param {MouseEvent} event - 触发的鼠标事件
 */
function startDragging(event) {
    isDragging.value = true;

    // 获取目标元素的位置信息
    const rect = event.target.getBoundingClientRect();
    // 计算鼠标点击位置相对于元素左上角的偏移量
    dragOffset.x = event.clientX - rect.left;
    dragOffset.y = event.clientY - rect.top;

    // 添加鼠标移动和释放事件监听器
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
}

/**
 * 鼠标移动时的处理函数
 * @param {MouseEvent} event - 触发的鼠标事件
 */
function onMouseMove(event) {
    if (!isDragging.value) return;

    // 计算新的鼠标位置，并减去初始偏移量
    const x = event.clientX - dragOffset.x;
    const y = event.clientY - dragOffset.y;

    // 设置新的位置
    toolPosition.top = `${y}px`;
    toolPosition.right = `${window.innerWidth - (x + rect().width)}px`;

    // 禁止文本选择，防止用户在拖动时选择页面内容
    document.body.style.userSelect = 'none';
}

/**
 * 鼠标释放时的处理函数
 */
function onMouseUp() {
    isDragging.value = false;
    // 移除鼠标移动和释放事件监听器
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
    // 恢复文本选择，允许用户选择页面内容
    document.body.style.userSelect = '';
}

/**
 * 获取工具容器的尺寸信息
 * @returns {DOMRect} - 元素的尺寸信息，如果没有找到元素则返回 { width: 0 }
 */
function rect() {
    const el = document.querySelector('.tool-copy-container');
    return el ? el.getBoundingClientRect() : {width: 0};
}

/**
 * 复制内容到指定平台
 * @param {Object} item - 平台信息对象
 */
function handleCopy(item) {
    if (item.title === 'juejin') {
        if (systemStore.copyJuejinWay) {
            handleSubmitJuejinTheme();
        } else {
            isShowJuejinConfirm.value = true;
        }
    } else if (item.title === 'csdn') {
        handleCopyMd('csdn');
    } else {
        const layout = document.getElementById('blueNote');
        const backupHTML = layout.innerHTML;
        solveWeChatMath();
        const copyHTML = solveHtml();
        copyToClipboard(copyHTML);
        layout.innerHTML = backupHTML;
        openPlatUrl('wechat');
    }
}

/** 直接复制MD文档内容 */
function handleCopyMd(way) {
    let wayName = tools.find(item => item.title === way).name;
    navigator.clipboard.writeText(props.text)
        .then(() => {
            ElMessage.success(`已复制到剪贴板，请去${wayName + '平台'}粘贴吧!`);
            openPlatUrl(way);
        })
        .catch(() => {
            ElMessage.warning(`复制失败，请手动复制!`);
        });
}

/** 复制掘金主题内容 */
function handleSubmitJuejinTheme() {
    const content = props.text;
    const frontMatter = `---\ntheme: ${juejinTheme.value}\n---\n`;
    const finalContent = frontMatter + content;

    navigator.clipboard.writeText(finalContent)
        .then(() => {
            ElMessage.success(`已复制为 ${juejinTheme.value} 格式，请去掘金平台粘贴吧!`);
            openPlatUrl('juejin')
        })
        .catch(() => {
            ElMessage.warning(`复制失败，请手动复制以下内容：${finalContent}`);
        })
        .finally(() => {
            isShowJuejinConfirm.value = false;
        });
}

/** 关闭掘金主题选择弹窗 */
function closeJuejinConfirm() {
    isShowJuejinConfirm.value = false;
}

function openPlatUrl(plat) {
    if (systemStore.openPlat) {
        setTimeout(() => {
            ElMessage({
                message: '请稍后，正在打开平台链接...',
                type: 'primary',
                plain: true,
            })
        }, 500)
        setTimeout(() => {
            let openUrl = tools.find(item => item.title === plat)?.url;
            if (systemStore.openPlat) {
                openUrl ? window.open(openUrl) : ElMessage.warning(`未找到 ${plat} 平台的链接，请自行打开`);
            }
        }, 2000);
    }
}
</script>

<style scoped lang="less">
.tool-copy-container {
    background-color: #fff;
    border: 1px solid #ddd;
    position: fixed;
    top: 50%;
    right: 20px;
}

.tool-copy-drag {
    width: 100%;
    text-align: center;
    cursor: all-scroll;
}

.tool-copy-item {
    margin: 5px 0;
    text-align: center;
    padding: 0 5px;
    box-sizing: border-box;
    cursor: pointer;
}

.juejin-theme-confirm {
    position: absolute;
    top: 50%;
    right: calc(100% + 15px);
    transform: translateY(-50%);
    width: 200px;
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 3px 6px;

    &::before {
        content: '';
        position: absolute;
        top: calc(50% + 2px);
        right: -14px;
        width: 14px;
        height: 16px;
        background-color: white;
        clip-path: polygon(0 0, 100% 50%, 0 100%);
        transform: translateY(-50%);
        z-index: 99;
    }

    /* 创建灰色边框的三角形 */

    &::after {
        content: '';
        position: absolute;
        top: calc(50% + 2px);
        right: -14px;
        width: 13px;
        height: 16px;
        background-color: #878787;
        clip-path: polygon(0 0, 100% 50%, 0 100%);
        transform: translateY(-50%);
    }

    .confirm-title {
        font-size: 12px;
        color: #878787;
        margin-bottom: 6px;
    }

    .confirm-footer {
        margin-top: 6px;
        display: flex;
        justify-content: flex-end;
    }
}
</style>